package com.appleyk.verify.interceptor;

import com.appleyk.core.ex.CommonException;
import com.appleyk.core.helper.LoggerHelper;
import com.appleyk.core.model.LicenseExtraParam;
import com.appleyk.core.model.LicenseResult;
import com.appleyk.core.model.LicenseVerifyManager;
import com.appleyk.core.result.ResultCode;
import com.appleyk.core.utils.CommonUtils;
import com.appleyk.verify.annotion.VLicense;
import com.appleyk.verify.config.LicenseVerifyProperties;
import com.appleyk.verify.listener.ACustomVerifyListener;
import de.schlichtherle.license.LicenseContent;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

/**
 * <p>License验证拦截器</p>
 *
 * @author appleyk
 * @version V.0.2.1
 * @blob https://blog.csdn.net/appleyk
 * @date created on 00:32 上午 2020/8/22
 */
public class LicenseVerifyInterceptor implements HandlerInterceptor {
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(LoggerHelper.class);
    @Autowired
    private LicenseVerifyProperties properties;

    public LicenseVerifyInterceptor() {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LicenseVerifyManager licenseVerifyManager = new LicenseVerifyManager();
        LicenseResult verifyResult = licenseVerifyManager.verify(properties.getVerifyParam());
        if(!verifyResult.getResult()){
            throw  new CommonException(verifyResult.getMessage());
        }
        LicenseContent content = verifyResult.getContent();
        LicenseExtraParam licenseCheck = (LicenseExtraParam) content.getExtra();
        if (verifyResult.getResult()) {
            return true;
        }else{
           /* response.setCharacterEncoding("utf-8");
            Map<String,String> result = new HashMap<>(1);
            result.put("result","您的证书无效，请核查服务器是否取得授权或重新申请证书！");

            response.getWriter().write(JSON.toJSONString(result));
*/
            logger.error("您的证书无效，请核查服务器是否取得授权或重新申请证书！");
            return false;
        }
    }
}
